#include<stdio.h>
#include<math.h>
struct student{
	char a[50];
	int score;
};
int main(int argc,char *argv[])
{
	char name[50];
	int t;
	scanf("%d",&t);
	int n,m;
	int i,j;
	while(t--)
	{
		scanf("%d %d",&n,&m);
		getchar();
		struct student stu[n+1];
		for(i=1;i<=n;i++)
		{
			scanf("%s",&stu[i].a);
			scanf("%d",&stu[i].score);
		}
		for(i=1;i<=m;i++)
		{
			scanf("%s",&name);
			for(j=1;j<=n;j++)
			{
				if(strcmp(stu[j].a,name)==0)
				{
					printf("%d\n",stu[j].score);
				}
			}
		}
	}
	return 0;
}
